package com.sso.dao.impl;

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.springframework.stereotype.Repository;

import com.sso.bean.entity.User;
import com.sso.dao.AuthticationDao;

@Repository("authticationDao")
public class AuthticationDaoImpl implements AuthticationDao {
	
	private static final ConcurrentHashMap<Long, User> db = new ConcurrentHashMap<Long, User>();
	
	ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

	static {
		db.put(10000L, new User(10000L, "ntwangshuai@126.com", "827ccb0eea8a706c4c34a16891f84e7b", ""));
		db.put(10001L, new User(10001L, "lichao@126.com", "827ccb0eea8a706c4c34a16891f84e7b", ""));
	}
	
	@Override
	public synchronized User getUserByUsername(String username) {
		User result = null;
		Iterator<User> iterator = db.values().iterator();
		while (iterator.hasNext()) {
			User user = iterator.next();
			if (user.getUsername().equals(username)) {
				result = user;
			}
		}
		return result;
	}
	
	@Override
	public User getUserById(long id) {
		User user = null;
		lock.readLock().lock();
		try {
			user = db.get(id);
		} finally {
			lock.readLock().unlock();
		}
		return user;
	}
	
	@Override
	public synchronized void updateTgcByUserId(long id, String tgc) {
		db.get(id).setTgc(tgc);
	}

	
}
